import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20*1000,
})
export interface responseType<T>{
  code:number,
  data:T,
  msg:string
}
export const request=<T>(url:string,method:Method='GET',submitData?:object)=>{
return service.request<T,responseType<T>>({
  url,
  method,
  [method.toUpperCase()==='GET'?'params':'data']:submitData
})
}
service.interceptors.request.use(
  config => {
    const userStore=useUserStore()
    if(userStore.token){
      config.headers.Authorization=`Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if(error.response){
    ElMessage.error(error.response.data.msg)
    if(error.response.status===401){
      router.push('/login')
      const store=useUserStore()
      store.clearToken()
    }
    }else{
      ElMessage.error('网络出错，请稍后再试')
    }
    return Promise.reject(error)
  },
)

export default service
